from pydub import AudioSegment
import shutil
import os


def merge_audio_files(input_file1, input_file2, output_file, insertion_time):
    # 读取两个音频文件
    audio1 = AudioSegment.from_file(input_file1)
    audio2 = AudioSegment.from_file(input_file2)

    # 将 m1 音频插入到 m2 的指定位置
    # insertion_point = insertion_time * 1000  # 将时间转换为毫秒
    merged_audio = audio2.overlay(audio1, position=int(insertion_time))

    # 保存合并后的音频文件
    merged_audio.export(output_file, format="wav")
    delete_file(input_file1)


def delete_file(file_path):
    if os.path.exists(file_path):
        os.remove(file_path)
        print(f"文件 {file_path} 已成功删除")
    else:
        print(f"文件 {file_path} 不存在")

def copy_file(source_file, destination_file):
    # 使用 shutil 的 copyfile 函数进行文件拷贝
    shutil.copyfile(source_file, destination_file)


def fileName(file_path):
    # 使用os.path.basename()获取文件名（含后缀）
    file_name_with_ext = os.path.basename(file_path)
    # 使用os.path.splitext()获取文件名和扩展名的拆分结果
    filename, ext = os.path.splitext(file_name_with_ext)
    return filename


# 获取音频文件
def audioFile(videoName):
    result_video = 'buff/7_merge_audio/' + videoName + '.wav'
    background_audio = 'buff/2_zmic_wav/' + videoName + '/accompaniment.wav'
    copy_file(background_audio, result_video)
    voice_audio = 'buff/5_wav/' + videoName
    for root, dirs, files in os.walk(voice_audio):
        for voice_audio in files:
            # 获取文件的完整路径
            wav_file_path = os.path.join(root, voice_audio)
            if wav_file_path.endswith('wav'):
                wavFileName = fileName(wav_file_path)
                times = wavFileName.split("-")
                merge_audio_files(wav_file_path, result_video, result_video, times[0])
    delete_directory(voice_audio)
    delete_directory('buff/2_zmic_wav/'+videoName)

def delete_directory(directory_path):
    try:
        # 删除目录及其内容
        shutil.rmtree(directory_path)
        print("目录删除成功")
    except Exception as e:
        print("目录删除失败:", e)

# 1 遍历原始视频目录
def deal_with_6_mp4_srt(fileDir):
    for root, dirs, files in os.walk(fileDir):
        for file in files:
            # 获取文件的完整路径
            video_file_path = os.path.join(root, file)

            # 获取文件的相对路径
            video_relative_path = os.path.relpath(video_file_path, fileDir)

            # 使用split()函数拆分相对路径，并将文件名的部分用下划线连接
            parts = video_relative_path.split(os.path.sep)
            formatted_name = '_'.join(parts)
            filename_without_ext = os.path.splitext(formatted_name)[0]
            # 打印格式化后的文件名
            # print(formatted_name)
            # print(filename_without_ext)
            if filename_without_ext == '.DS_Store':
                continue;
            audioFile(filename_without_ext)



# 遍历目录"6_mp4_srt"下的文件,就是想找到下一个要处理文件的名称，不用纠结这个文件的名字
deal_with_6_mp4_srt("buff/6_mp4_srt")
